package com.fangyu.lottery.service;

import com.fangyu.lottery.model.DistributionLog;
import com.fangyu.lottery.model.PrizeDistributionMessage;
import lombok.Data;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author fangyu
 * @version v1.0.0
 * @since 2025/8/27 23:48
 */
@Service
@Slf4j
public class PrizeService {

    @Autowired
    private CouponService couponService;

    @Autowired
    private PointService pointService;

    @Autowired
    private PhysicalPrizeService physicalPrizeService;

    @Autowired
    private DistributionLogRepository distributionLogRepository;

    /**
     * 发放优惠券奖品
     */
    public void distributeCoupon(Long userId, Long prizeId) {
        try {
            log.info("开始发放优惠券奖品, userId: {}, prizeId: {}", userId, prizeId);

            // 1. 查询奖品详情
            Coupon coupon = getCouponDetail(prizeId);
            if (coupon == null) {
                throw new RuntimeException("优惠券不存在, prizeId: " + prizeId);
            }

            // 2. 调用优惠券系统发放优惠券
            boolean result = couponService.issueCoupon(userId, coupon.getCouponCode());

            if (result) {
                log.info("优惠券发放成功, userId: {}, prizeId: {}", userId, prizeId);
            } else {
                throw new RuntimeException("优惠券发放失败, userId: " + userId + ", prizeId: " + prizeId);
            }

        } catch (Exception e) {
            log.error("发放优惠券奖品异常, userId: {}, prizeId: {}", userId, prizeId, e);
            throw new RuntimeException("发放优惠券奖品失败", e);
        }
    }

    /**
     * 发放积分奖品
     */
    public void distributePoints(Long userId, Long prizeId) {
        try {
            log.info("开始发放积分奖品, userId: {}, prizeId: {}", userId, prizeId);

            // 1. 查询奖品详情
            PointPrize pointPrize = getPointDetail(prizeId);
            if (pointPrize == null) {
                throw new RuntimeException("积分奖品不存在, prizeId: " + prizeId);
            }

            // 2. 调用积分系统增加积分
            boolean result = pointService.addPoints(userId, pointPrize.getPointValue(),
                    "活动奖励:" + pointPrize.getName());

            if (result) {
                log.info("积分发放成功, userId: {}, prizeId: {}", userId, prizeId);
            } else {
                throw new RuntimeException("积分发放失败, userId: " + userId + ", prizeId: " + prizeId);
            }

        } catch (Exception e) {
            log.error("发放积分奖品异常, userId: {}, prizeId: {}", userId, prizeId, e);
            throw new RuntimeException("发放积分奖品失败", e);
        }
    }

    /**
     * 发放实物奖品
     */
    public void distributePhysicalPrize(Long userId, Long prizeId) {
        try {
            log.info("开始发放实物奖品, userId: {}, prizeId: {}", userId, prizeId);

            // 1. 查询奖品详情
            PhysicalPrize physicalPrize = getPhysicalPrizeDetail(prizeId);
            if (physicalPrize == null) {
                throw new RuntimeException("实物奖品不存在, prizeId: " + prizeId);
            }

            // 2. 生成物流订单
            String orderNo = physicalPrizeService.createShippingOrder(userId, physicalPrize);

            log.info("实物奖品发货单已生成, userId: {}, prizeId: {}, orderNo: {}",
                    userId, prizeId, orderNo);

        } catch (Exception e) {
            log.error("发放实物奖品异常, userId: {}, prizeId: {}", userId, prizeId, e);
            throw new RuntimeException("发放实物奖品失败", e);
        }
    }

    /**
     * 记录奖品发放日志
     */
    public void recordDistributionLog(PrizeDistributionMessage message) {
        try {
            DistributionLog log = new DistributionLog();
            log.setActivityId(message.getActivityId());
            log.setUserId(message.getUserId());
            log.setPrizeId(message.getPrizeId());
            log.setPrizeType(message.getPrizeType());
            log.setDistributeTime(message.getDistributeTime());
            log.setStatus("SUCCESS");
            log.setCreateTime(new Date());

            distributionLogRepository.save(log);

        } catch (Exception e) {
            // 记录日志失败不应影响主流程，但需要记录错误
            log.error("记录奖品发放日志失败: {}", message, e);
        }
    }

    /**
     * 查询优惠券详情 (模拟实现)
     */
    private Coupon getCouponDetail(Long prizeId) {
        // 这里应该是从数据库或缓存中查询
        // 简化实现，直接返回模拟数据
        Coupon coupon = new Coupon();
        coupon.setId(prizeId);
        coupon.setName("10元优惠券");
        coupon.setCouponCode("COUPON_" + prizeId + "_" + System.currentTimeMillis());
        coupon.setValue(10.0);
        coupon.setExpireDays(30);
        return coupon;
    }

    /**
     * 查询积分奖品详情 (模拟实现)
     */
    private PointPrize getPointDetail(Long prizeId) {
        // 这里应该是从数据库或缓存中查询
        // 简化实现，直接返回模拟数据
        PointPrize pointPrize = new PointPrize();
        pointPrize.setId(prizeId);
        pointPrize.setName("100积分");
        pointPrize.setPointValue(100);
        return pointPrize;
    }

    /**
     * 查询实物奖品详情 (模拟实现)
     */
    private PhysicalPrize getPhysicalPrizeDetail(Long prizeId) {
        // 这里应该是从数据库或缓存中查询
        // 简化实现，直接返回模拟数据
        PhysicalPrize physicalPrize = new PhysicalPrize();
        physicalPrize.setId(prizeId);
        physicalPrize.setName("定制水杯");
        physicalPrize.setSku("SKU_001");
        physicalPrize.setWeight(0.5);
        return physicalPrize;
    }

    // 数据模型
    @Data
    public static class Coupon {
        private Long id;
        private String name;
        private String couponCode;
        private Double value;
        private Integer expireDays;
    }

    @Data
    public static class PointPrize {
        private Long id;
        private String name;
        private Integer pointValue;
    }

    @Data
    public static class PhysicalPrize {
        private Long id;
        private String name;
        private String sku;
        private Double weight;
    }
}